package com.practise.rabbitmqdemo.listen;

import com.practise.rabbitmqdemo.config.DirectRabbitConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DirectReceiver {

    @RabbitListener(queues = {DirectRabbitConfig.QUEUE_1})
    public void processQueue1(String msg) {
        System.out.println("QUEUE_1 DirectReceiver消费者收到消息  : " + msg);
    }

    @RabbitListener(queues = DirectRabbitConfig.QUEUE_11,ackMode ="MANUAL")
    public void processQueue11(String msg , Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {

        try {
            // 处理实际业务
            // 制造异常
            // int wrongNumber = 1/0;
            // 无异常，确认消息消费成功
            channel.basicAck(deliveryTag, true);
            System.out.println("deliveryTag: "+deliveryTag+" processQueue11 DirectReceiver消费者收到消息  : " + msg);
        }catch (IOException | ArithmeticException exception) {
            // 有异常，将消息返回给Queue里，第三个参数requeue可以直接看出来，是否返回到Queue中
            System.out.println("DirectReceiver消费者收到消息 有异常  ");
            channel.basicNack(deliveryTag, true, true);
        }
    }
}